import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface UserInfo {
  id: number
  username: string
  email: string
  avatar?: string
  roles: string[]
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref<UserInfo | null>(null)
  const token = ref<string>('')
  const isLoggedIn = ref<boolean>(false)

  // 计算属性
  const hasRole = computed(() => {
    return (role: string) => {
      return userInfo.value?.roles.includes(role) || false
    }
  })

  const displayName = computed(() => {
    return userInfo.value?.username || '游客'
  })

  // 方法
  const setToken = (newToken: string) => {
    token.value = newToken
    isLoggedIn.value = !!newToken
    if (newToken) {
      localStorage.setItem('token', newToken)
    } else {
      localStorage.removeItem('token')
    }
  }

  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info
  }

  const login = async (username: string, password: string) => {
    try {
      // 这里应该调用实际的登录API
      // const response = await loginAPI(username, password)
      
      // 模拟登录成功
      const mockUser: UserInfo = {
        id: 1,
        username,
        email: `${username}@example.com`,
        roles: ['user']
      }
      
      setUserInfo(mockUser)
      setToken('mock-token-' + Date.now())
      
      return { success: true, message: '登录成功' }
    } catch (error) {
      return { success: false, message: '登录失败' }
    }
  }

  const logout = () => {
    userInfo.value = null
    setToken('')
    isLoggedIn.value = false
  }

  const initializeAuth = () => {
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      setToken(savedToken)
      // 这里可以验证token有效性
    }
  }

  return {
    // 状态
    userInfo,
    token,
    isLoggedIn,
    // 计算属性
    hasRole,
    displayName,
    // 方法
    setToken,
    setUserInfo,
    login,
    logout,
    initializeAuth
  }
}, {
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['userInfo', 'token', 'isLoggedIn']
  }
}) 